import os
import re
import hashlib
from typing import List, Tuple
from urllib.parse import quote

def is_image_file(filename: str) -> bool:
    """检查文件是否为支持的图片格式"""
    supported_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'}
    return os.path.splitext(filename.lower())[1] in supported_extensions

def get_natural_sort_key(text: str) -> List:
    """
    生成自然排序的键，用于正确排序包含数字的文件名
    例如: img1.jpg, img2.jpg, img10.jpg 而不是 img1.jpg, img10.jpg, img2.jpg
    """
    def convert(part):
        return int(part) if part.isdigit() else part.lower()
    
    return [convert(c) for c in re.split('([0-9]+)', text)]

def sort_files_naturally(filenames: List[str]) -> List[str]:
    """对文件名进行自然排序"""
    return sorted(filenames, key=get_natural_sort_key)

def sort_paths_naturally(paths: List[str]) -> List[str]:
    """对路径进行自然排序"""
    return sorted(paths, key=lambda x: get_natural_sort_key(os.path.basename(x)))

def generate_id_from_path(path: str) -> str:
    """根据路径生成唯一ID"""
    return hashlib.md5(path.encode('utf-8')).hexdigest()

def safe_filename(filename: str) -> str:
    """生成安全的文件名"""
    # 移除或替换不安全的字符
    safe_chars = re.sub(r'[<>:"/\\|?*]', '_', filename)
    return safe_chars.strip()

def get_file_size_str(size_bytes: int) -> str:
    """将字节大小转换为可读的字符串"""
    if size_bytes == 0:
        return "0B"
    
    size_names = ["B", "KB", "MB", "GB", "TB"]
    i = 0
    while size_bytes >= 1024.0 and i < len(size_names) - 1:
        size_bytes /= 1024.0
        i += 1
    
    return f"{size_bytes:.1f}{size_names[i]}"

def normalize_path(path: str) -> str:
    """标准化路径"""
    return os.path.normpath(path).replace('\\', '/')

def is_subdirectory(child_path: str, parent_path: str) -> bool:
    """检查是否为子目录"""
    try:
        parent_path = os.path.abspath(parent_path)
        child_path = os.path.abspath(child_path)
        return child_path.startswith(parent_path + os.sep) or child_path == parent_path
    except (OSError, ValueError):
        return False

def url_safe_path(path: str) -> str:
    """生成URL安全的路径"""
    return quote(normalize_path(path), safe='/')

def extract_title_from_path(path: str) -> str:
    """从路径中提取标题"""
    basename = os.path.basename(path)
    # 移除文件扩展名（如果是文件）
    if os.path.isfile(path):
        basename = os.path.splitext(basename)[0]
    
    # 清理标题
    title = basename.replace('_', ' ').replace('-', ' ')
    title = re.sub(r'\s+', ' ', title).strip()
    
    return title or basename

def get_directory_size(directory: str) -> int:
    """计算目录大小"""
    total_size = 0
    try:
        for dirpath, dirnames, filenames in os.walk(directory):
            for filename in filenames:
                filepath = os.path.join(dirpath, filename)
                try:
                    total_size += os.path.getsize(filepath)
                except OSError:
                    continue
    except OSError:
        pass
    return total_size

def find_cover_image(directory: str) -> str:
    """在目录中查找封面图片"""
    if not os.path.isdir(directory):
        return ""
    
    # 优先查找的文件名模式
    cover_patterns = [
        'cover.*', 'Cover.*', 'COVER.*',
        'front.*', 'Front.*', 'FRONT.*',
        '001.*', '01.*', '1.*',
        'page001.*', 'page01.*', 'page1.*'
    ]
    
    try:
        files = os.listdir(directory)
        image_files = [f for f in files if is_image_file(f)]
        
        if not image_files:
            return ""
        
        # 按优先级查找封面
        for pattern in cover_patterns:
            import fnmatch
            matches = fnmatch.filter(image_files, pattern)
            if matches:
                return os.path.join(directory, sort_files_naturally(matches)[0])
        
        # 如果没找到特定封面，返回第一个图片文件
        sorted_images = sort_files_naturally(image_files)
        return os.path.join(directory, sorted_images[0])
        
    except OSError:
        return ""

def validate_comic_directory(directory: str) -> Tuple[bool, str]:
    """验证是否为有效的漫画目录"""
    if not os.path.exists(directory):
        return False, "目录不存在"
    
    if not os.path.isdir(directory):
        return False, "不是有效的目录"
    
    try:
        files = os.listdir(directory)
        image_files = [f for f in files if is_image_file(f)]
        
        if not image_files:
            return False, "目录中没有图片文件"
        
        return True, "有效的漫画目录"
        
    except PermissionError:
        return False, "没有访问权限"
    except OSError as e:
        return False, f"读取目录失败: {str(e)}"

def clean_cache_filename(filename: str) -> str:
    """清理缓存文件名"""
    # 移除路径分隔符和特殊字符
    clean_name = re.sub(r'[<>:"/\\|?*]', '_', filename)
    clean_name = clean_name.replace(' ', '_')
    return clean_name

def ensure_directory_exists(directory: str) -> bool:
    """确保目录存在"""
    try:
        os.makedirs(directory, exist_ok=True)
        return True
    except OSError:
        return False